<template>
  <!-- 天气信息 -->
  <!-- <BaseSvgIcon style="font-size:240px;" :icon="'mai'" /> -->
  <div class="weather-info-wrapper">
    <!-- <BaseSvgIcon
      style="font-size: 420px"
      :icon="'mai'"
    /> -->
    <span class="date-info">
      {{ weatherInfo.dateWithWeek }}
    </span>
    <span class="situation-info">
      <span class="first">{{ weatherInfo.temperature || 0 }}°C</span>
      <span class="second">{{ weatherInfo.weather }}</span>
    </span>
    <!-- <span class="tip-info">
      {{ greetingText }}
    </span> -->
  </div>
</template>

<script>
import Moment from 'moment'
import { timeFix } from '@/utils/util.js'

export default {
  name: 'WeatherView',
  data() {
    return {
      weatherInfo: {} // 天气信息
    }
  },
  computed: {
    greetingText() {
      return `${timeFix()}`
    },
    getBgIcon() {
      const weather = this.weatherInfo.weather || ''
      if (weather.indexOf('晴') > -1) {
        return 'qing'
      }
      if (weather.indexOf('云') > -1) {
        return 'yun'
      }
      if (weather.indexOf('雨') > -1) {
        return 'yu'
      }
      if (weather.indexOf('雪') > -1) {
        return 'xue'
      }
      if (weather.indexOf('霾') > -1) {
        return 'mai'
      }
      return 'yun'
    }
  },
  created() {
    this.getWeather()
  },
  methods: {
    /**
     * 获取天气相关信息
     */
    getWeather() {
      const momentInstance = Moment()
      const now = momentInstance.format('YYYY-MM-DD HH:mm:ss')
      const cache = localStorage.getItem('weatherInfo')
      const month = momentInstance.month() // 0-11
      const day = momentInstance.date() // 1-31
      const week = momentInstance.weekday() // 0-6
      const map = {
        0: '一',
        1: '二',
        2: '三',
        3: '四',
        4: '五',
        5: '六',
        6: '日'
      }
      if (cache) {
        try {
          const weatherInfo = JSON.parse(cache)
          // 计算当前时间距离上次获取到天气过去多久了，在一定时间段内直接取缓存数据（moment用seconds单位获取差值，确保时间的准确性）
          const diff = Moment(now).diff(Moment(weatherInfo.setDate), 'seconds') / 60 / 60
          // 3小时内取缓存数据
          if (diff < 3) {
            this.weatherInfo = weatherInfo
            return
          }
        } catch (e) {
          console.error(e)
        }
      }
      const key = 'b2120bb08dbaf6ebe628171a7706921c' // 高德地图的应用key值
      fetch(`https://restapi.amap.com/v3/ip?key=${key}`)
        .then((response) => response.json())
        .then((res) => {
          if (res.status === '1') {
            const cityId = res.adcode // 城市编码（高德地图天气）
            fetch(`https://restapi.amap.com/v3/weather/weatherInfo?key=${key}&city=${cityId}`)
              .then((response) => response.json())
              .then((weatherRes) => {
                if (weatherRes.status === '1') {
                  const info = (weatherRes.lives && weatherRes.lives[0]) || {}
                  this.weatherInfo = {
                    ...info,
                    setDate: now,
                    dateWithWeek: `${month > 9 ? month : month + 1}月${day}日 星期${map[week]}`
                  }
                  localStorage.setItem('weatherInfo', JSON.stringify(this.weatherInfo))
                }
              })
          }
        })
    }
  }
}
</script>

<style lang="less" scoped>
.weather-info-wrapper {
  padding: 0 0 0 20px;
  width: 100%;
  height: 60px;
  line-height: 60px;
  display: flex;
  align-items: center;
  background: url('~@/assets/indexPage/weather-bg.png');
  background-size: 100% 100%;
  color: #ffffff;
  .date-info {
    font-size: 16px;
    opacity: 0.8;
  }
  .situation-info {
    padding: 8px 0;
    margin-left: 20px;
    .first {
      font-size: 36px;
      color: #fff9c1;
    }
    .second {
      font-size: 20px;
      margin-left: 20px;
    }
  }
  .tip-info {
    opacity: 0.8;
    font-size: 12px;
  }
}
</style>